package top.csy8888.ch09.common;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import top.csy8888.ch09.vo.Chat;
import top.csy8888.ch09.vo.Message;
import top.csy8888.ch09.vo.Online;

/**
 * @author wangl
 * @date 2025/9/18
 */
public class MessageUtils {

    private final static ObjectMapper mapper = new ObjectMapper();

    public static String createMessage(Online online) {
        Message<Online> message = new Message<>();
        message.setType("total");
        message.setMessage(online);
        return toJSon(message);
    }

    public static String createMessage(Chat chat) {
        Message<Chat> message = new Message<>();
        message.setType("chat");
        message.setMessage(chat);
        return toJSon(message);
    }

    private static String toJSon(Message<?> message) {
        try {
            return mapper.writeValueAsString(message);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}